package com.es.esapi.utils;

import com.alibaba.fastjson.JSON;
import com.es.esapi.domain.ClassA;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class txttojson {


    /**
     * txt文件读取并转成JSON格式
     *
     * @return
     */

    public List<ClassA> txt_to_json() throws IOException {
        String time = new PdfConvertUtil().gettime();
        InputStreamReader ins = new InputStreamReader(new FileInputStream("C://solve//txt//"+time+".txt"));
        BufferedReader br = new BufferedReader(ins);
        //存放bean对象
        List<ClassA> tlist = new ArrayList<ClassA>();

        //读取txt
        String line = null;
        List<String> list = new ArrayList<String>();
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        System.out.println(list);
        br.close();
        String st = "";
        int i=1;
        //txt的每一行相当于一条数据，split按空格作分隔符进行拆分。\\s+是正则表达式。
        for (String str : list) {
            //String[] arrStr = str.split("\\s+");
            ClassA classA = new ClassA();
            //判断页数，进行分页提取
            if (str.matches("^[0-9]+$")) {
                classA.setRealpage(str);
                classA.setPage(i);
                classA.setContent(st);
                tlist.add(classA);
                i=i+1;
                st = "";
            }
            st = st.concat(str);
            st = st.concat(" ");

        }
        System.out.println("txt_to_json");
        System.out.println(tlist);
        //JSON.toJSONString()方法：将对象数组（JSON格式的字符串也可以）转换成JSON数据。
        String json = JSON.toJSONString(tlist);

        //创建新文件
        File txtToJson = new File("C://solve//JSON//"+time+".json");
        txtToJson.createNewFile();
        BufferedWriter out = new BufferedWriter(new FileWriter(txtToJson));
        out.write(json);
        out.flush(); // 把缓存区内容压入文件
        out.close(); // 最后记得关闭文件
        return tlist;
    }


    public String getfilename(String filename) throws IOException {
        String time = new PdfConvertUtil().gettime();
        String st="";
        st=st.concat(time);
        return  st;

    }
}
